package com.smart.es.service.impl;

import com.smart.es.entity.Product;
import com.smart.es.service.ProductService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProductServiceImpl implements ProductService {
    @Resource
    ElasticsearchRestTemplate template;

    @Override
    public List<Product> list(int page, int size, String name, String title) {
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();

        WildcardQueryBuilder nameQuery = QueryBuilders.wildcardQuery("name", String.format("*%s*", name));

        WildcardQueryBuilder titleQuery = QueryBuilders.wildcardQuery("title", String.format("*%s*", title));


        bqb.should(nameQuery).should(titleQuery);

        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withPageable(PageRequest.of(page, size))
                .withQuery(bqb)
                .build();
        SearchHits<Product> hits = template.search(query, Product.class);
        List<Product> products = hits.stream().map(SearchHit::getContent)
                .collect(Collectors.toList());
        return products;
    }
}
